package com.lmt.api;

import com.lmt.base.ResultData;
import com.lmt.entity.Collection;
import com.lmt.entity.search.CollectionSearch;
import com.lmt.service.CollectionService;
import com.lmt.service.ResourceEsService;
import com.lmt.util.CheckResult;
import com.lmt.util.RedisCacheUtil;
import com.lmt.util.SystemConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Date 2018/07/17
 *
 * @author MT-Lin
 */
@RestController
@RequestMapping("/CollectionApi")
public class CollectionApi {

	private final CollectionService collectionService;

	private final ResourceEsService resourceEsService;

	private final RedisCacheUtil redisCacheUtil;

	@Autowired
	public CollectionApi(CollectionService collectionService, ResourceEsService resourceEsService, RedisCacheUtil redisCacheUtil) {
		this.collectionService = collectionService;
		this.resourceEsService = resourceEsService;
		this.redisCacheUtil = redisCacheUtil;
	}

	@RequestMapping("/delete")
	public ResultData delete(@RequestBody List<Collection> collections) {
		return this.collectionService.delete(collections);
	}

	@RequestMapping("/update")
	public ResultData update(@RequestBody Collection collection) {
		return this.collectionService.update(collection);
	}

	@RequestMapping("/search")
	public ResultData search(@RequestBody CollectionSearch collectionSearch) {
		collectionSearch.setCreator(redisCacheUtil.getUserId(collectionSearch));
		return this.collectionService.search(collectionSearch);
	}

	@RequestMapping("/isCollected")
	public ResultData isCollected(@RequestBody CollectionSearch collectionSearch) {
		collectionSearch.setCreator(redisCacheUtil.getUserId(collectionSearch));
		return this.collectionService.isCollected(collectionSearch);
	}

	@RequestMapping("/collectResource")
	public ResultData collectResource(@RequestBody Collection collection) {
		collection.setCreator(redisCacheUtil.getUserId(collection));
		ResultData result = this.collectionService.save(collection);
		if (CheckResult.isSuccess(result)) {
			this.resourceEsService.updateCollectionNum(collection.getObjId(), SystemConstant.COLLECTION_OPERATION_ADD);
		}
		return result;
	}

	@RequestMapping("/cancelCollectResource")
	public ResultData cancelCollectResource(@RequestBody Collection collection) {
		collection.setCreator(redisCacheUtil.getUserId(collection));
		ResultData result = this.collectionService.delete(collection);
		if (CheckResult.isSuccess(result)) {
			this.resourceEsService.updateCollectionNum(collection.getObjId(), SystemConstant.COLLECTION_OPERATION_CANCEL);
		}
		return result;
	}
}
